/**
 * 列配置本地存储工具
 * 用于保存和恢复表格列的宽度和排序信息
 */

export interface ColumnConfig {
  key: string;
  width: number;
  order: number; // 列的顺序
}

export interface TableConfig {
  columns: ColumnConfig[];
  sortState?: {
    field: string | null;
    order: 'ascend' | 'descend' | null;
  };
}

/**
 * 获取localStorage中的表格配置
 * @param tableKey 表格的唯一标识符
 * @returns 表格配置或null
 */
export const getTableConfig = (tableKey: string): TableConfig | null => {
  try {
    const configStr = localStorage.getItem(`table_config_${tableKey}`);
    if (configStr) {
      return JSON.parse(configStr);
    }
  } catch (error) {
    console.warn('Failed to parse table config from localStorage:', error);
  }
  return null;
};

/**
 * 保存表格配置到localStorage
 * @param tableKey 表格的唯一标识符
 * @param config 表格配置
 */
export const saveTableConfig = (tableKey: string, config: TableConfig): void => {
  try {
    localStorage.setItem(`table_config_${tableKey}`, JSON.stringify(config));
  } catch (error) {
    console.warn('Failed to save table config to localStorage:', error);
  }
};

/**
 * 从列配置中恢复列宽度和顺序
 * @param originalColumns 原始列配置
 * @param tableKey 表格的唯一标识符
 * @returns 恢复后的列配置
 */
export const restoreColumns = (originalColumns: any[], tableKey: string): any[] => {
  const savedConfig = getTableConfig(tableKey);
  if (!savedConfig || !savedConfig.columns) {
    return originalColumns;
  }

  // 创建列配置映射
  const columnConfigMap = new Map(
    savedConfig.columns.map(config => [config.key, config])
  );

  // 恢复列配置
  const restoredColumns = originalColumns.map(column => {
    const savedConfig = columnConfigMap.get(column.key);
    if (savedConfig) {
      return {
        ...column,
        width: savedConfig.width
      };
    }
    return column;
  });

  // 按保存的顺序重新排列
  const sortedColumns = [...restoredColumns].sort((a, b) => {
    const configA = columnConfigMap.get(a.key);
    const configB = columnConfigMap.get(b.key);
    
    if (!configA || !configB) return 0;
    return configA.order - configB.order;
  });

  return sortedColumns;
};

/**
 * 保存列配置到localStorage
 * @param columns 当前列配置
 * @param tableKey 表格的唯一标识符
 * @param sortState 排序状态（可选）
 */
export const saveColumns = (
  columns: any[], 
  tableKey: string, 
  sortState?: { field: string | null; order: 'ascend' | 'descend' | null }
): void => {
  const columnConfigs: ColumnConfig[] = columns.map((column, index) => ({
    key: column.key,
    width: column.width || 100,
    order: index
  }));

  const config: TableConfig = {
    columns: columnConfigs,
    sortState
  };

  saveTableConfig(tableKey, config);
};

/**
 * 获取保存的排序状态
 * @param tableKey 表格的唯一标识符
 * @returns 排序状态或null
 */
export const getSortState = (tableKey: string): { field: string | null; order: 'ascend' | 'descend' | null } | null => {
  const config = getTableConfig(tableKey);
  return config?.sortState || null;
};

/**
 * 清除表格配置
 * @param tableKey 表格的唯一标识符
 */
export const clearTableConfig = (tableKey: string): void => {
  try {
    localStorage.removeItem(`table_config_${tableKey}`);
  } catch (error) {
    console.warn('Failed to clear table config from localStorage:', error);
  }
};
